# 简化的开发证书生成脚本
param(
    [switch]$Deploy = $false
)

function Write-Info($Message, $Color = "White") {
    Write-Host $Message -ForegroundColor $Color
}

Write-Info "================================================" "Cyan"
Write-Info "   WebRTC 开发证书生成工具" "Cyan"
Write-Info "================================================" "Cyan"

try {
    # 创建证书目录
    if (!(Test-Path "certs")) {
        New-Item -ItemType Directory -Path "certs"
        Write-Info "✅ 创建证书目录: certs" "Green"
    }

    Write-Info "🔐 生成开发者证书..." "Blue"
    
    # 清理可能存在的证书
    dotnet dev-certs https --clean 2>$null
    
    # 生成新的开发者证书
    dotnet dev-certs https --trust 2>$null
    
    # 导出证书到文件
    $password = "webrtc123"
    $pfxPath = "certs\webrtc-dev.pfx"
    
    dotnet dev-certs https -ep $pfxPath -p $password --trust
    
    if (Test-Path $pfxPath) {
        Write-Info "✅ 开发证书生成成功!" "Green"
        Write-Info "   - 证书文件: $pfxPath" "Cyan"
        Write-Info "   - 证书密码: $password" "Yellow"
        
        # 更新 Docker Compose 配置
        Write-Info "🔧 更新 Docker Compose 配置..." "Blue"
        
        $content = Get-Content "docker-compose.yml" -Raw
        $content = $content -replace 'webrtc-dev\.pfx', 'webrtc-dev.pfx'
        $content = $content -replace 'Password=.*', "Password=$password"
        Set-Content "docker-compose.yml" -Value $content -Encoding UTF8
        
        Write-Info "✅ 配置已更新" "Green"
        
        if ($Deploy) {
            Write-Info "🚀 部署应用..." "Blue"
            
            # 停止现有容器
            docker-compose down 2>$null
            
            # 构建并启动
            docker-compose up -d --build
            
            if ($LASTEXITCODE -eq 0) {
                Write-Info "✅ 应用部署成功!" "Green"
                Write-Info "📱 访问地址:" "Cyan"
                Write-Info "   - HTTPS: https://localhost:5001 (推荐用于WebRTC)" "Green"
                Write-Info "   - HTTP:  http://localhost:5000" "Yellow"
                Write-Info ""
                Write-Info "⚠️  首次访问HTTPS可能需要在浏览器中接受证书" "Yellow"
            } else {
                Write-Info "❌ 部署失败，查看日志:" "Red"
                docker-compose logs --tail=20
            }
        } else {
            Write-Info "💡 运行以下命令来部署应用:" "Yellow"
            Write-Info "   docker-compose up -d --build" "Cyan"
            Write-Info ""
            Write-Info "📱 部署后访问:" "Cyan"
            Write-Info "   - HTTPS: https://localhost:5001 (推荐用于WebRTC)" "Green"
        }
    } else {
        Write-Info "❌ 证书生成失败" "Red"
        exit 1
    }
}
catch {
    Write-Info "❌ 执行失败: $($_.Exception.Message)" "Red"
    Write-Info ""
    Write-Info "💡 替代方案 - 手动生成证书:" "Yellow"
    Write-Info "   1. 运行: dotnet dev-certs https --trust" "Cyan"
    Write-Info "   2. 运行: dotnet dev-certs https -ep certs\webrtc-dev.pfx -p webrtc123" "Cyan"
    Write-Info "   3. 运行: docker-compose up -d --build" "Cyan"
    exit 1
} 